package co2.bean;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.id.UUIDHexGenerator;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import co2.engine.Co2Constants;
import co2.engine.DAOInterface;


@ManagedBean
@ViewScoped
public class FileUploadBean extends AbstractBean implements Serializable {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	@Qualifier("daoI")
	private DAOInterface dao;
	private List<co2.pojos.FileUpload> list;
	private UploadedFile uploadFile; 
	private co2.pojos.FileUpload cofu;
	private co2.pojos.FileUpload cofu2;
	private StreamedContent file;
	
	
	@PostConstruct
	public void postCon(){
		cofu = new co2.pojos.FileUpload();
		list = dao.getAllFileUpload();
	}
	
	public void upload(){

		StringBuffer sb = new StringBuffer();
		sb.append(Co2Constants.UPLOAD_FILE_LKS_PATH).append(uploadFile.getFileName());
		File file = new File(sb.toString());
		try{
			OutputStream out = new FileOutputStream(file);
			out.write(uploadFile.getContents());
			cofu.setPath(Co2Constants.DOWNLOAD_PATH+file.getName());
			cofu.setFilename(file.getName());
			out.close();
			
			cofu.setId(new UUIDHexGenerator().generate(null, null).toString());
			cofu.setCreateDate(new Timestamp(new Date().getTime()));
			dao.save(cofu);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Upload Sukses",""));
			list = dao.getAllFileUpload();
		}catch(Exception e){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error!", "Upload Failed!!\n"+e.getMessage()));
			e.printStackTrace();
		}
	
	}
	
	public void downloadFile() throws IOException{
	    FacesContext facesContext = FacesContext.getCurrentInstance();
	    ExternalContext externalContext = facesContext.getExternalContext();
	    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

	    File file = new File(cofu.getPath());

	    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
	    response.setContentType("application/vnd.ms-excel"); // Check http://www.w3schools.com/media/media_mimeref.asp for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
	    response.setHeader("Content-disposition", "attachment; filename=\""+file.getName()+"\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.

	    BufferedInputStream input = null;
	    BufferedOutputStream output = null;
	    

	    try {
	        input = new BufferedInputStream(new FileInputStream(file));
	        output = new BufferedOutputStream(response.getOutputStream());

	        byte[] buffer = new byte[10240];
	        for (int length; (length = input.read(buffer)) > 0;) {
	            output.write(buffer, 0, length);
	        }
	    } finally {
	       output.close();
	       input.close();
	    }

	    facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
	}
	
	public void delete(){
		try{
			dao.delete(co2.pojos.FileUpload.class, cofu.getId());
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Hapus Sukses",""));
			list = dao.getAllFileUpload();
		}catch(Exception e){
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Hapus gagal",""));
			e.printStackTrace();
		}
	}

	public DAOInterface getDao() {
		return dao;
	}

	public void setDao(DAOInterface dao) {
		this.dao = dao;
	}

	public List<co2.pojos.FileUpload> getList() {
		return list;
	}

	public void setList(List<co2.pojos.FileUpload> list) {
		this.list = list;
	}

	public UploadedFile getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(UploadedFile uploadFile) {
		this.uploadFile = uploadFile;
	}

	public co2.pojos.FileUpload getCofu() {
		return cofu;
	}

	public void setCofu(co2.pojos.FileUpload cofu) {
		this.cofu = cofu;
	}

	public co2.pojos.FileUpload getCofu2() {
		return cofu2;
	}

	public void setCofu2(co2.pojos.FileUpload cofu2) {
		this.cofu2 = cofu2;
		
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	

}
